import 'babel-polyfill'
import sourceMapSupport from 'source-map-support'
sourceMapSupport.install({
    environment: 'node'
});

import express from "express";
import http from "http";
import preprocessor from './utils/http_preprocess';
import persistent from './persistent';

export default async function (opts) {

    process.on('unhandledRejection', (reason, p) => {
        console.warn('Unhandled Rejection at: Promise', p, 'reason:', reason);
    });
    console.log("HTTP Server Starting...");
    let app = express();
    let server = http.Server(app);
    server.listen(opts.port, function () {
        let host = server.address().address;
        let port = server.address().port;
        console.log('HTTP server listening at http://%s:%s', host, port);
    });


    //Load WebAPI Modules:
    let wrapHttp = fn => ((...args) => fn(...args).catch(e => {
        console.log("HTTP Error:", e);
        console.log(e.stack);
        args[1].json({error: e});
    }));
    let ctx = {
        app,
        get: (path, fn) => app.get(path, wrapHttp(fn)),
        post: (path, fn) => app.post(path, wrapHttp(fn)),
        server
    };

    ctx.app.all("/1", (req,res)=>{
        res.json({test:"1"});
    });
    await preprocessor(ctx);
    await persistent(ctx);

    return ctx;
}